#include "wave_atom.h"
#include <cmath>
using namespace std;

vector<double> Sine::MakeWaveTable ( int repeat, double rangeMax, double rangeMin ) const
{
    double circle = sampleRate / freq * repeat;
    int icircle = int ( circle + 0.5 );
    vector<double> table ( icircle ) ;
    for ( int i = 0 ; i < icircle; ++i )
    {
        table[i] = ( sin ( i * freq / sampleRate * 2.0 * M_PI ) + 1.0 ) / 2.0 * ( rangeMax - rangeMin ) + rangeMin;
    }
    return table;
}

bool AlignedSine::Align ( int minLoop, int maxLoop, bool strict )
{
    if ( maxLoop == 0 )
    {
        maxLoop = int ( 1.0 / thres ) + minLoop;
    }
    //loop = FindProperLoops(minLoop, minLoop + int( 1.0 / thres ) );
    double circle;
    int icircle;
    double error;
    double minError = 1.0;
    double newFreq = freq;
    for ( int i = minLoop; i <= maxLoop; ++i )
    {
        circle = sampleRate / freq * i;
        icircle = int ( circle + 0.5 );
        error = circle - icircle;
        if ( (!strict || abs ( error ) <= thres) && abs ( error ) < minError )
        {
            minError = abs ( error );
            loop = i;
            newFreq = sampleRate * loop / icircle;
        }
    }
    freq = newFreq;

    return ( minError < thres );
}

